package util;

import Contant.Constant;
import book.Book;
import com.bit.utils.FileUtils;

import java.io.IOException;
import java.time.LocalDate;

public class AnalyzingBook {

    //这个方法是将Book数组对象存储到文件中
    public void storeObject(Book[]books,String filename)throws IOException{
        //先遍历books数组,看不为空的数据有多少个（统计数组中有效元素数量）
        int bookUseLen=0;
        for (int i=0;i<books.length;i++){
            if(books[i]!=null){
                bookUseLen++;
            }
        }
        //jsonArray用于拼接存储书籍信息的JSON内容
        StringBuilder jsonArray=new StringBuilder() ;
        for (int i = 0; i <bookUseLen ; i++) {
            if (books[i]!=null){
                jsonArray.append(books[i].toJSON());
                if (i!=bookUseLen-1){
                    jsonArray.append("\n");
                }
            }
        }
        FileUtils.writeFile(jsonArray.toString(),filename); //将数据写入文件中
    }
    //这个方法是从文件读取数据并转换为Book数组
    public Book[] loadObject(String filename)throws IOException{
        String content=FileUtils.readFile(filename); //将文件内容读取到content中
        if (content==null||content.isEmpty()){
            System.out.println("File is empty or dose exist"+filename);//检查content是否为空,是的话就返回null(空）
        }
        String[] bookJsonStrings=content.split("\n");//使用\n作为分隔符进行字符串分割
        Book[] bookList=new Book[bookJsonStrings.length];//用于储存解析后的书籍对象
        for (int i = 0; i < bookJsonStrings.length ; i++) {
            //调用parseBookJson方法，将当前字符串（如JSON格式的书籍数据）解析为Book对象
            Book book=parseBookJson(bookJsonStrings[i]);
            bookList[i]=book;//将解析后的Book对象储存到bookList数组的对应位置
        }
        return bookList;
    }
    //这个方法是解析（parse）包含书籍信息的JSON字符串并转换为Book对象
    private Book parseBookJson(String json) {
        String[] pairs = json.split(",");
        //Book book = new Book();
        //for (int i = 0; i < pairs.length; i++) {
        int bookId = Integer.parseInt(pairs[0]);
        String title = pairs[1];
        String author = pairs[2];
        String category = pairs[3];
        int publishYear = Integer.parseInt(pairs[4]);
        boolean isBorrowed = Boolean.parseBoolean(pairs[5]);//shift+tab    tab
        int borrowCount = Integer.parseInt(pairs[6]);
        LocalDate shelfDate = LocalDate.parse(pairs[7]);
        //}
        //构造书籍对象
        if (title != null && author != null && category != null && shelfDate != null) {
            Book book = new Book(title, author, category, publishYear, shelfDate);
            book.setBookId(bookId);
            book.setBorrowed(isBorrowed);
            book.setBorrowedCount(borrowCount);
            return book;
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        AnalyzingBook myProperties=new AnalyzingBook();
        //存储数据
        Book[] books=new Book[4];
        books[0] = new Book("java", "gaobo", "编程", 1994, LocalDate.of(2023, 9, 24));
        books[1] = new Book("mysql", "lisi", "编程", 1999, LocalDate.of(2024, 2, 10));
        books[2] = new Book("php", "gaobo", "编程", 2020, LocalDate.of(2023, 9, 23));
        books[3] = new Book("西游记", "吴承恩", "小说", 2024, LocalDate.of(2023, 9, 23));
        try {
            myProperties.storeObject(books, Constant.ALL_BOOK_FILE_NAME);
            //读取数据
            Book[] loadedBooks=myProperties.loadObject(Constant.ALL_BOOK_FILE_NAME);
            if(loadedBooks!=null){
                System.out.println("Loaded books:");
                for (int i = 0; i < loadedBooks.length ; i++) {
                    System.out.println(loadedBooks[i]);  //将数据打印出来
                }
            }

        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

